<template>
  <div class="device-detail-page">
    <el-page-header @back="goBack" title="返回">
      <template #content>
        <span class="page-title">设备详情</span>
      </template>
    </el-page-header>

    <div v-loading="loading" class="detail-content">
      <!-- 基本信息 -->
      <el-card shadow="never" class="info-card">
        <template #header>
          <div class="card-header">
            <span>基本信息</span>
            <el-tag :type="device.status === 'online' ? 'success' : 'info'">
              {{ device.status === 'online' ? '在线' : '离线' }}
            </el-tag>
          </div>
        </template>
        <el-descriptions :column="2" border>
          <el-descriptions-item label="设备ID">
            {{ device.deviceId }}
          </el-descriptions-item>
          <el-descriptions-item label="设备名称">
            {{ device.deviceName }}
          </el-descriptions-item>
          <el-descriptions-item label="IP地址">
            {{ device.ipAddress || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="当前状态">
            <el-tag :type="device.status === 'online' ? 'success' : 'info'">
              {{ device.status === 'online' ? '在线' : '离线' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="最后上线时间">
            {{ formatTime(device.lastOnlineTime) }}
          </el-descriptions-item>
          <el-descriptions-item label="最后心跳时间">
            {{ formatTime(device.lastHeartbeatTime) }}
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">
            {{ formatTime(device.createdAt) }}
          </el-descriptions-item>
          <el-descriptions-item label="更新时间">
            {{ formatTime(device.updatedAt) }}
          </el-descriptions-item>
        </el-descriptions>
      </el-card>

      <!-- Tab切换 -->
      <el-card shadow="never" class="tab-card">
        <el-tabs v-model="activeTab">
          <!-- 设备日志 -->
          <el-tab-pane label="设备日志" name="logs">
            <div class="toolbar">
              <el-select
                v-model="logEventType"
                placeholder="事件类型"
                style="width: 150px"
                @change="fetchLogs"
              >
                <el-option label="全部" value="" />
                <el-option label="上线" value="online" />
                <el-option label="离线" value="offline" />
                <el-option label="配置" value="config" />
              </el-select>
              <el-button :icon="Refresh" @click="fetchLogs">刷新</el-button>
            </div>
            <el-table
              v-loading="logsLoading"
              :data="logs"
              style="width: 100%"
            >
              <el-table-column prop="eventType" label="事件类型" width="120">
                <template #default="{ row }">
                  <el-tag
                    :type="row.eventType === 'online' ? 'success' : row.eventType === 'offline' ? 'info' : 'warning'"
                  >
                    {{ row.eventType }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="message" label="日志信息" />
              <el-table-column label="时间" width="200">
                <template #default="{ row }">
                  {{ formatTime(row.timestamp) }}
                </template>
              </el-table-column>
            </el-table>
            <div class="pagination">
              <el-pagination
                v-model:current-page="logsPagination.page"
                v-model:page-size="logsPagination.pageSize"
                :total="logsPagination.total"
                :page-sizes="[10, 20, 50]"
                layout="total, sizes, prev, pager, next"
                @current-change="fetchLogs"
                @size-change="fetchLogs"
              />
            </div>
          </el-tab-pane>

          <!-- 心跳历史 -->
          <el-tab-pane label="心跳历史" name="heartbeats">
            <div class="toolbar">
              <el-button :icon="Refresh" @click="fetchHeartbeats">刷新</el-button>
            </div>
            <el-table
              v-loading="heartbeatsLoading"
              :data="heartbeats"
              style="width: 100%"
            >
              <el-table-column label="状态" width="120">
                <template #default="{ row }">
                  <el-tag type="success">
                    {{ row.payload.status }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="负载数据">
                <template #default="{ row }">
                  {{ JSON.stringify(row.payload) }}
                </template>
              </el-table-column>
              <el-table-column label="时间" width="200">
                <template #default="{ row }">
                  {{ formatTime(row.timestamp) }}
                </template>
              </el-table-column>
            </el-table>
            <div class="pagination">
              <el-pagination
                v-model:current-page="heartbeatsPagination.page"
                v-model:page-size="heartbeatsPagination.pageSize"
                :total="heartbeatsPagination.total"
                :page-sizes="[10, 20, 50]"
                layout="total, sizes, prev, pager, next"
                @current-change="fetchHeartbeats"
                @size-change="fetchHeartbeats"
              />
            </div>
          </el-tab-pane>
        </el-tabs>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { Refresh } from '@element-plus/icons-vue'
import { getDeviceDetail, getDeviceLogs, getDeviceHeartbeats } from '@/api/device'
import { formatTime } from '@/utils/format'

const route = useRoute()
const router = useRouter()
const deviceId = route.params.id

// 设备信息
const loading = ref(false)
const device = ref({})

// Tab
const activeTab = ref('logs')

// 日志
const logsLoading = ref(false)
const logs = ref([])
const logEventType = ref('')
const logsPagination = reactive({
  page: 1,
  pageSize: 20,
  total: 0
})

// 心跳
const heartbeatsLoading = ref(false)
const heartbeats = ref([])
const heartbeatsPagination = reactive({
  page: 1,
  pageSize: 20,
  total: 0
})

// 返回
const goBack = () => {
  router.back()
}

// 获取设备详情
const fetchDevice = async () => {
  loading.value = true
  try {
    const res = await getDeviceDetail(deviceId)
    device.value = res.data
  } catch (error) {
    console.error('获取设备详情失败:', error)
  } finally {
    loading.value = false
  }
}

// 获取日志
const fetchLogs = async () => {
  logsLoading.value = true
  try {
    const params = {
      page: logsPagination.page,
      pageSize: logsPagination.pageSize
    }
    if (logEventType.value) {
      params.eventType = logEventType.value
    }
    const res = await getDeviceLogs(deviceId, params)
    logs.value = res.data.list
    logsPagination.total = res.data.total
  } catch (error) {
    console.error('获取日志失败:', error)
  } finally {
    logsLoading.value = false
  }
}

// 获取心跳历史
const fetchHeartbeats = async () => {
  heartbeatsLoading.value = true
  try {
    const params = {
      page: heartbeatsPagination.page,
      pageSize: heartbeatsPagination.pageSize
    }
    const res = await getDeviceHeartbeats(deviceId, params)
    heartbeats.value = res.data.list
    heartbeatsPagination.total = res.data.total
  } catch (error) {
    console.error('获取心跳历史失败:', error)
  } finally {
    heartbeatsLoading.value = false
  }
}

// 定时刷新
let timer = null
onMounted(() => {
  fetchDevice()
  fetchLogs()
  // 每10秒刷新一次设备信息
  timer = setInterval(fetchDevice, 10000)
})

onUnmounted(() => {
  if (timer) {
    clearInterval(timer)
  }
})
</script>

<style scoped>
.device-detail-page {
  height: 100%;
}

.page-title {
  font-size: 18px;
  font-weight: 500;
}

.detail-content {
  margin-top: 20px;
}

.info-card,
.tab-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.toolbar {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>

